const ws = require('nodejs-websocket');
const fs = require('fs');
const http = require('http');

var ws_list = [];
var base_url = 'http://127.0.0.1/c/ws_lib/';

function get_uid_subindex(conn) {
	var conn_uri = conn.path.substr(1);
	var conn_param = conn_uri.split('/');
	var uid = parseInt(conn_param[0]);
	var sub_index = parseInt(conn_param[1]);
	return [uid, sub_index];
}

function remove_conn(conn) {
	var params = get_uid_subindex(conn);
	delete ws_list[params[0]][params[1]];
}

function rt(remaining_time, id) {
	remaining_time -= 2147483647;
	if (remaining_time > 2147483647) {
		setTimeout(rt, 2147483647, remaining_time, id);
	} else {
		setTimeout(function (id) {
			http.get(base_url + 'group_topic_reset.php?id=' + id);
		}, remaining_time, id);
	}
}

function ws_server(conn) {
	var params = get_uid_subindex(conn);
	if (ws_list[params[0]] === undefined) {
		ws_list[params[0]] = [];
	}
	ws_list[params[0]][params[1]] = conn;
	var list = [];
	for (var i = 0; i < ws_list[params[0]].length; ++i) {
		if (ws_list[params[0]][i] === undefined) {
			list.push('');
		} else {
			list.push(i);
		}
	}
	var txt_name = './ws_session/' + params[0] + '.txt';
	fs.writeFileSync(txt_name, list.join('|'));

	conn.on('text', function (data) {
		var array = data.split('";"');
		var d = {};
		const keys = ['receive_group_id', 'receive_id', 'msg', 'group_topic_id_timer'];
		for (var i in array) {
			var array2 = array[i].split('"="');
			var key = array2[0], value = array2[1];
			if (keys.indexOf(key) === -1) {
				conn.sendText('fail:命令不存在');
				return;
			}
			d[key] = value;
		}
		if (d['group_topic_id_timer'] !== undefined && d['group_topic_id_timer'] !== null) {
			var group_timer_txt = './group_topic_time.txt';
			var current_mseconds = Date.now();
			var group_timer_text = fs.readFileSync(group_timer_txt).toString();
			fs.writeFileSync(group_timer_txt, group_timer_text + '\n' + 
				d['group_topic_id_timer'] + '-' + current_mseconds.toString() + '\n');
			rt(25920000000, d['group_topic_id_timer']);
			return;
		}
		var params = get_uid_subindex(conn);
		var uid = params[0];
		var ret_str = 'send_id"="' + uid + '";"msg"="' + d['msg'];
		if (d['receive_group_id'] !== undefined && d['receive_group_id'] !== null) {
			receive_group_id = parseInt(d['receive_group_id']);
			var group_txt_name = './ws_group/' + receive_group_id + '.txt';
			var session_list = fs.readFileSync(group_txt_name).toString().split('|');
			for (var i in session_list) {
				var v = session_list[i];
				for (var j in ws_list[v]) {
					ws_list[v][j].sendText(ret_str);
				}
			}
		}
		if (d['receive_id'] !== undefined && d['receive_id'] !== null) {
			var receive_id = parseInt(d['receive_id']);
			if (receive_id === 0) {
				for (var i in ws_list) {
					for (var j in ws_list[i]) {
						if (ws_list[i][j] !== undefined) {
							ws_list[i][j].sendText(ret_str);
						}
					}
				}
			} else {
				for (var i in ws_list[receive_id]) {
					if (ws_list[receive_id][i] !== undefined) {
						ws_list[receive_id][i].sendText(ret_str);
					}
				}
			}
		}
	});

	conn.on('close', function (e) {
		var params = get_uid_subindex(conn);
		remove_conn(conn);
		var txt_name = './ws_session/' + params[0] + '.txt';
		var list = [];
		var is_all_empty = true;
		var is_change = false;
		for (var i = 0; i < ws_list[params[0]].length; ++i) {
			if (ws_list[params[0]][i] === undefined) {
				list.push('');
			} else {
				if (!is_change) {
					is_all_empty = false;
					is_change = true;
				}
				list.push(i);
			}
		}
		if (is_all_empty) {
			ws_list[params[0]] = [];
			fs.writeFileSync(txt_name, '');
		} else {
			fs.writeFileSync(txt_name, list.join('|'));
		}
	});
	conn.on('error', function (err) {
		if (err.code !== 'ECONNRESET') {
			console.error(err);
		}
	});
}

var group_topic_time_list = fs.readFileSync('group_topic_time.txt').toString().split('\n');
var surplus_list = [];
for (var i in group_topic_time_list) {
	if (group_topic_time_list[i] === '') {
		continue;
	}
	var info = group_topic_time_list[i].split('-');
	var id = info[0];
	var time = parseInt(info[1]);
	var remaining_time = 300 * 24 * 60 * 60 * 1000 - (Date.now() - time);
	if (remaining_time <= 0) {
		http.get(base_url + 'group_topic_reset.php?id=' + id);
	} else {
		surplus_list.push(group_topic_time_list[i]);
		setTimeout(function () {
			http.get(base_url + 'group_topic_reset.php?id=' + id);
		}, remaining_time);
		rt(remaining_time, id);
	}
}
fs.writeFileSync('group_topic_time.txt', surplus_list.join('\n'));

ws.createServer(ws_server).listen(2048);
